<template>
	<view class="">
		<view class="common-body" v-for="(item,index) in baseList" :key="index">
			<u-collapse style="border: 1px solid #EAEAEA;">
				<u-collapse-item>
					<template v-slot:title>
						<view style="font-weight: bold;margin-left: 5px;">冲销说明</view>
					</template>
					<view>
						如果预估单有首付款且数量为0，那么全量冲销进度款时请先冲销首付款，再冲销进度款！
					</view>
				</u-collapse-item>
			</u-collapse>
			<view class="common-list">

				<label class="common-list-title">供应商名称 :</label>

				<text class="common-list-text" :selectable="true">{{item.supplierName}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">订单编号 :</label>

				<text class="common-list-text" :selectable="true">{{item.orderCode}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">合同编码 :</label>

				<text class="common-list-text" :selectable="true">{{item.contractCode}}</text>

			</view>
			<view class="common-list">
				<view style="width:50%;">
					<label class="common-list-title">订单状态 :</label>

					<text class="common-list-text">{{orderStatus[item.orderState] || orderStatus['default']}}</text>
				</view>
				<view style="width:50%;margin-left: 20px;">
					<label class="common-list-title">录入计价次数 :</label>

					<text class="common-list-text">{{item.valuationDetails.length}}</text>
				</view>

			</view>
			<view class="common-list">

				<label class="common-list-title">商合预占数 :</label>

				<text class="common-list-text">{{item.shNum}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">单价（元） :</label>

				<text class="common-list-text">{{item.price}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">商合预占金额 :</label>

				<text class="common-list-text">{{item.shMoney}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">累计验工数量 :</label>

				<text class="common-list-text">{{item.sumNum}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">累计验工金额 :</label>

				<text class="common-list-text">{{item.sumMoney}}</text>

			</view>
		</view>


		<!-- 填写区 -->
		<view class="common-body-ex">
			<view class="common-list-ex">

				<label class="common-list-title-ex">付款类型 :</label>
				<view class="">
          <radio-group>
            <label class="radio">
              <radio value="FIRST" :checked="true" />首付款（含安全生产费）
            </label>
          </radio-group>
				</view>
			</view>
			<view class="common-list-ex" style="background-color: #FFFBE5;">

				<label class="common-list-title-ex"><text class="colorRed">*</text>项目进度(%) :</label>

				<input @input="inputClick" class="common-list-inpur-ex" type="digit" :disabled="this.form.payType==='FIRST'"  v-model="form.projectProgress"
					placeholder="请输入" />

			</view>
			<view class="common-list-ex"  style="background-color: #FFFBE5;">

				<label class="common-list-title-ex"><text class="colorRed">*</text>本期冲销数量 :</label>

				<input
          @input="blurclick"
          class="common-list-inpur-ex"
          type="digit"
          v-model="form.currentInspectionNum"
          :disabled='true'
          placeholder="请输入"
        />

			</view>

			<view class="common-list-ex"  style="background-color: #FFFBE5;">

				<label class="common-list-title-ex"><text class="colorRed">*</text>本期冲销金额 :</label>

				<input
          @input="blurclickMen"
          class="common-list-inpur-ex"
          type="digit"
          v-model="form.currentInspectionMoney"
          placeholder="请输入"
          :disabled='true'
        />

			</view>
			<!-- <view class="common-list-ex">
			
				<label class="common-list-title-ex">单价（元） :</label>
			
				<text class="common-list-text-ex">{{item.value7}}</text>
			
		</view> -->

			<view class="common-list-ex">

				<label class="common-list-title-ex">累计验工数量 :</label>

				<text class="common-list-text-ex">{{form.sumNum}}</text>

			</view>
			<view class="common-list-ex">

				<label class="common-list-title-ex">累计验工金额 :</label>

				<text class="common-list-text-ex">{{form.sumMoney}}</text>

			</view>
		</view>

		<view class="common-btn-body">
			<button class="common-btn" style='width: 160px' type="warn" v-debounce="save">推送商合</button>
			<button class="common-btn" @click="quxiao()" style="border:1px solid #EB4B4B;color:#EB4B4B ;">取消</button>
		</view>

	</view>
</template>

<script>
	import talkingdata from '../../common/talkingdata.js';
  import {postApi} from "@/inspur/utils/request";
	var mThis
  const orderStatus = {
    '1':'有效',
    '0':'无效',
    '-1':'冻结',
    'default':'取消冻结'
  }
	export default {
		data() {
			return {
        orderStatus,
        form:{
          payType: 'FIRST',
          projectProgress: '0', // 进度
          currentInspectionNum: '', // 本期数量
          currentInspectionMoney: '', // 本期金额
          sumNum: '', // 累计数量
          sumMoney: '', // 累计金额
        },
				checked: true,
				checked2: false,
        isEdit: false,
				radioList: [{
						name: '进度款',
						value: "jindu"
					},
					{
						name: '收付款（含安全生产费）',
						disabled: "shoufu"
					}
				],
        isNew: false,
				baseList: [],
				addlist: [],
				alerts: '',
				accordion: false,
        
        valuationId: '',
				currentjindu: '0',
				currentNum: '',
				currentMen: '',
				disabledNum: false,
				disabledMen: false,
				leijiNum: '0',
				leijiMen: '0',
				itemStyle:{
					border:'1px solid #EAEAEA',
				},
			}
		},
		onLoad({valuationId,isNew,isEdit}) {
			this.valuationId = valuationId
      this.isEdit = JSON.parse(isEdit)
      this.isNew = JSON.parse(isNew)
			this.getList()
		},
		onReady(){
			console.log("执行onReady")
			
			//在页面挂载完成后，调用外部埋点，统计数据
			 const script= document.createElement('script');
			 script.type = 'text/javascript';
			 script.src = talkingdata.talkingKey;
			 document.body.appendChild(script);
			
		},
		// onBackPress(options) {
		// 	if (options.from === 'navigateBack') {
		// 		console.log("触发1")
		// 		return false;
		// 	}
		// 	console.log("触发2")
		// 	this.back();
		// 	return true;
		// },
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				});
			},	
	
			quxiao() {
        uni.navigateBack({
          delta: 1
        })
			},
      // 计算本期验工金额
      setCurrentInspectionMoney(){
        this.form.currentInspectionMoney = this.formatNumber(this.form.currentInspectionNum * this.baseList[0].price)
      },
      // 计算累计验工数量
      setSumNum(){
        this.form.sumNum = Number(this.form.currentInspectionNum) + Number(this.baseList[0].sumNum)
      },
      // 计算累计验工金额
      setSumMoney(){
        this.form.sumMoney =  this.formatNumber(Number(this.form.currentInspectionMoney) + Number(this.baseList[0].sumMoney))
      },
			inputClick() {
        // 0-100的整数
        let price = JSON.parse(JSON.stringify(this.form.projectProgress));
        price = price
          .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
          .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
          .replace(".", "$#$")
          .replace(/\./g, "")
          .replace("$#$", ".")
          .replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
        if (price.indexOf(".") < 0 && price != "") {
          // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          price = parseFloat(price);
        }
        
        if (price>100) {price = 100}
        if (price<0) {price = 0}
        else {this.setCurrentInspectionMoney()}
        setTimeout(() => {
          this.form.projectProgress = price;
        }, 100)


			},
      formatNumber(num,v=2) {
        if (Number.isInteger(num)) {
          return num; // 如果是整数，直接返回整数
        } else {
          const str = num.toString();
          const decimalIndex = str.indexOf('.');
          if (decimalIndex !== -1 && str.length - decimalIndex > 3) {
            return Number(str.slice(0, decimalIndex + 3));
          } else {
            return num;
          }
        }
      },
			blurclick() {
				//控制保留4位start
        let val = Number(this.form.currentInspectionNum);
        if (this.isNew){
          val = this.formatNumber(val, this.baseList[0].spuUnitAcc)
        }else{
          val = this.formatNumber(val, 4)
        }
        if (val>0){ val = -val}
				setTimeout(() => {
          this.form.currentInspectionNum = val;
				}, 100)
				//end
        return;
        //这块之前就有return，下面应该是无效代码，修改严重问题时候注释掉
				//冲销的金额和数量不大于付款类型为进度款的累积的金额和数量
				// if (this.currentNum != undefined && this.currentNum != "") {
				// 	let that = this
				// if(Number(this.currentNum)>Number(this.baseList[0].sumNum)){
				// 	uni.showModal({confirmColor: '#eb4b4b',
				// 		title: '温馨提示',
				// 		content: "进度款的冲销的金额和数量不大于累积的金额和数量",
				// 		showCancel: false,
				// 		success: function(res) {
				// 			if (res.confirm) {
				//
				// 				that.currentNum = "";
				// 				that.currentMen = "";
				// 				that.leijiNum = '0';
				// 				that.leijiMen = '0';
				// 			}
				// 		}
				// 	})
				//
				// 	return;
				// }
				// }
				//
				// if (this.baseList[0].onlyBe1Flag == "N") {
				// 	if (this.currentNum != undefined && this.currentNum != "") {
				// 		this.currentMen = this.baseList[0].price * this.currentNum
				// 		this.currentMen = this.currentMen.toFixed(4); // 只能输入四个小数
				// 		this.leijiNum = Number(this.baseList[0].sumNum) - Number(this.currentNum)
				// 		this.leijiNum = this.leijiNum.toFixed(4); // 只能输入四个小数
				// 		if (this.currentMen) {
				// 			console.log("触发");
				// 			this.leijiMen = Number(this.baseList[0].sumMoney) - Number(this.currentMen)
				// 			this.leijiMen = this.leijiMen.toFixed(4) //只能输入四个小数
				// 		}
				//
				// 		if (this.baseList[0].sumNum !== this.baseList[0].shNum && this.baseList[0].sumNum !== 0) {
				//
				// 			this.menflag = this.currentMen
				// 			console.log("等于1触发" + this.menflag);
				// 			console.log("可以修改");
				// 		} else {
				// 			console.log("不能修改");
				// 			this.disabledMen = true
				// 		}
				//
				// 	}
				//
				// }

			},
      farmatMoney(money) { // 四舍五入保留2位小数
        var pum = 0
        var value = ''
        if (money < 0) {
          pum = -money
        } else {
          pum = money
        }
        value = Math.round(pum * Math.pow(10, 2)) / Math.pow(10, 2)
        // if (this.newOldProject === '1') {
        //   value = Math.round(pum * Math.pow(10, 9)) / Math.pow(10, 9)
        // } else {
        //   value = Number(pum)
        // }
        if (money < 0) {
          return -value
        } else {
          return value
        }
      },
			blurclickMen() {
				console.log("触发")
				//控制保留4位start
        let val = Number(this.form.currentInspectionMoney);
        val = this.formatNumber(val, 2)
        console.log("1触发校验"+val)
        setTimeout(() => {
          this.form.currentInspectionMoney = val;
          this.setSumMoney()
        }, 100)
        return
				//end
        // return
				// if (this.baseList[0].onlyBe1Flag == "N") {
        //
				// 	if (this.currentNum == "1" && this.currentMen != "") {
				// 		if (Number(this.currentMen) > (Number(this.menflag) + 10) || Number(this.currentMen) < (Number(this
				// 				.menflag) + 10)) {
				// 			console.log("出错");
				// 			uni.showModal({confirmColor: '#eb4b4b',
				// 				title: '温馨提示',
				// 				content: '验工计价金额只能在系统计算的合价范围内上下浮动10元',
				// 				showCancel: false,
				// 				success: function(res) {
				// 					if (res.confirm) {
				// 						this.currentNum = this.menflag.toFixed(4)
        //
				// 					}
				// 				}
				// 			})
				// 		}
				// 	}
				// }
				// this.leijiMen = Number(this.baseList[0].sumMoney) - Number(this.currentMen)
				// this.leijiMen = this.leijiMen.toFixed(4)
			},
			/**
			 * @author: MrLiu
			 * @time: 2021-09-15
			 * @Title: 工序详情
			 */
      getList() {
        let that = this
        postApi('/material/api/insVa/app/queryValDetailsByVid',{params:{valuationId:this.valuationId}}).then(res=>{
          that.baseList = res.data.valuationInfo
          const valuationDetails = res.data.valuationInfo[0].valuationDetails
          const xList = valuationDetails.filter(item=>item.payType=='FIRST')
          that.form.projectProgress = 100
          that.form.currentInspectionNum = -Number(xList[0].currentInspectionNum)
          that.form.currentInspectionMoney = -Number(xList[0].currentInspectionMoney)
          that.form.sumNum = 0
          that.form.sumMoney = 0
        })
      },
			/**
			 * @author: MrLiu
			 * @time: 2021-11-23
			 * @Title: 保存
			 */
			save() {
        let that = this
        const valuationDetails = this.baseList[0].valuationDetails
        const detail = valuationDetails[valuationDetails.length-1]
        uni.showModal({confirmColor: '#eb4b4b',
          title: '温馨提示',
          content: "当前验工计价将推送商合交易",
          success: function (res1) {
            if (res1.confirm) {
              const data = {
                "vId": detail?.valuationDetailId,
                "parentValId": that.baseList[0].parentValuationId,
                "pId":  that.baseList[0].valuationId,
                "prjId": that.baseList[0].prjId,
                "subPrjId": that.baseList[0].subPrjId,
                "onlyBe1Flag": that.baseList[0].onlyBe1Flag,
                "siteId": that.baseList[0].siteId,
                "serviceCode": that.baseList[0].serviceCode,
                "reduceNum": -Number(detail.currentInspectionNum),
                "reduceMoney": -Number(detail.currentInspectionMoney),
                "currentInspectionNum": 0,
                "currentInspectionMoney": 0,
                "sumMoney": that.baseList[0].sumMoney,
                "sumNum": that.baseList[0].sumNum,
                "inspectionTax": 0,
                "inspectionTaxAmount": 0,
                "orderDetailId": that.baseList[0].orderDetailId,
                "purchaseMode": that.baseList[0].purchaseMode,
                "payType": detail.payType,
                "flag": "1"
              }
              postApi('/material/api/insVa/module/updateInspectionValuOverallPro', {data}).then(res => {
                uni.showModal({confirmColor: '#eb4b4b',
                  title: '温馨提示',
                  content: res.message,
                  showCancel: false,
                  success: function () {
                    uni.navigateBack({
                      delta: 1
                    })
                  }
                })
              })
            }
          }
        })

			},
			radioChange(e) {
        this.form.payType = e.detail.value
        if (e.detail.value === 'FIRST'){
          this.form.projectProgress = 100
        }
			},
			radioChange2() {

				this.checked = false
				this.checked2 = true
				console.log(this.checked + "触发2" + this.checked2)
				
				for (var i = 0; i < this.baseList[0].valuationDetails.length; i++) {
					if ('FIRST' == this.baseList[0].valuationDetails[i].payType) {
						this.currentNum = this.baseList[0].valuationDetails[i].currentInspectionNum
						this.currentMen = this.baseList[0].valuationDetails[i].currentInspectionMoney
						this.disabledNum = true
						this.disabledMen = true
						this.leijiNum = Number(this.baseList[0].sumNum) - Number(this.currentNum)
						this.leijiMen = Number(this.baseList[0].sumMoney) - Number(this.currentMen)
						return;
					}
				
				}
				
			},
			chuliNum(params) {

				let newpar = parseFloat(params);

				let reg = /^[0-9]+.?[0-9]*$/;

				if (reg.test(newpar)) {

					let newNum = newpar.toFixed(3);

					return newNum;

				} else {

					alert('请输入数字');

					return;

				}

			}


		}
	}
</script>


<style>
	@import '@/common/common-ui.css';
</style>
